package com.hmall.trade.listener;


import com.hmall.api.client.pay.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.common.constants.MqConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {
    private final IOrderService orderService;
    private final PayClient payClient;

   @RabbitListener(bindings = @QueueBinding(
        value = @Queue(name = MqConstants.DELAY_ORDER_QUEUE_NAME),
        exchange = @Exchange(name = MqConstants.DELAY_EXCHANGE_NAME, delayed = "true"),
        key = MqConstants.DELAY_ORDER_KEY
))
public void listenOrderDelayMessage(Long orderId) {
    // 查询订单
    Order order = orderService.getById(orderId);
    // 检查订单是否存在且仍处于未支付状态(status = 1)
    if (order == null || order.getStatus() != 1) {
        return;
    }

    // 查询支付服务中的支付状态
    PayOrderDTO payOrderDTO = payClient.queryPayOrderByBizOrderNo(orderId);

    // 如果支付成功，更新订单状态
    if (payOrderDTO != null && payOrderDTO.getStatus() == 3) {
        orderService.markOrderPaySuccess(orderId);
        return;
    }

    // 如果支付服务不可用或支付未成功，取消订单
    orderService.cancelOrder(orderId);
}

}
